//
//  ZWRefreshControl.swift
//  ZWWeibo
//
//  Created by flyiron on 16/4/23.
//  Copyright © 2016年 flyiron. All rights reserved.
//

import UIKit

class ZWRefreshControl: UIControl {
    private let RefreshViewH: CGFloat = 50
    
    enum ZWRefreshControlState: String{
        case Normal = "普通"
        case Pulling = "下拉刷新"
        case Refreshing = "刷新中"
    }
    
    var zwState: ZWRefreshControlState = .Normal {
        didSet{
            
            switch zwState {
            case .Pulling:
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowImage.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                msgLabel.text = "松手刷新"
            case .Refreshing:
                self.arrowImage.hidden = true
                self.indecatorView.startAnimating()
                msgLabel.text = "正在刷新"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.tableView?.contentInset.top =  self.tableView!.contentInset.top + self.RefreshViewH
                })
                self.sendActionsForControlEvents(UIControlEvents.ValueChanged)
            case .Normal:
                self.indecatorView.stopAnimating()
                self.arrowImage.hidden = false
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowImage.transform = CGAffineTransformIdentity
                })
                msgLabel.text = "等待刷新"
                if oldValue == .Refreshing {
                    UIView.animateWithDuration(0.25) { () -> Void in
                        self.tableView?.contentInset.top = self.tableView!.contentInset.top - self.RefreshViewH
                    }
                }
            }
        }
    }
    

    
    var tableView:UIScrollView?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        backgroundColor = UIColor.orangeColor()
        self.frame.size.width = SCREENW
        self.frame.size.height = RefreshViewH
        self.frame.origin.y = -RefreshViewH
        
        addSubview(arrowImage)
        addSubview(msgLabel)
        addSubview(indecatorView)
        

        arrowImage.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self).offset(-35)
            make.centerY.equalTo(self)
        }
        msgLabel.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(arrowImage)
            make.leading.equalTo(arrowImage.snp_trailing)
        }
        
        indecatorView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowImage)
        }

    }
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        guard let tableView = newSuperview as? UIScrollView else {
            return
        }
        self.tableView = tableView
        tableView.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)

    }
    
    deinit {
        tableView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    func endRefreshing(){
        zwState = .Normal
       
    }
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
//        print(change)
        let contentOffset = self.tableView!.contentOffset
        let conditionValue = -tableView!.contentInset.top - RefreshViewH
//        print(tableView?.contentInset)
        if tableView!.dragging {
            if contentOffset.y < conditionValue && zwState == .Normal {
                print("控件完全显示出来了")
                zwState = .Pulling
            }else{
                if contentOffset.y >= conditionValue && zwState == .Pulling {
                    print("控件没有完全显示出来了")
                    zwState = .Normal
                }
            }
        }else{
            if zwState == .Pulling {
                print("控件进行刷新中")
                zwState = .Refreshing
            }
        }
    }
    
    
    private lazy var arrowImage: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    private lazy var msgLabel: UILabel = {
        let label = UILabel(textColor: UIColor.darkGrayColor(), fontSize: 12)
        label.text = "等待起飞"
        return label
    }()
    
    private lazy var indecatorView: UIActivityIndicatorView = UIActivityIndicatorView()
}
